<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use zgldh\QiniuStorage\QiniuStorage;
use App\Shop;
use App\Sclass;
use Input;
use App\ShopArticle;
class ShopController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        /**
         * @time 2017-12-09
         * @author Kowy
         * @tool Phpstorm
         * @company Try
         */
        $datas = Shop::paginate('30');
        $now_time = time();
        return view('admin.shop.index',compact('datas','now_time'));

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        /**
         * @author kowy
         * @time   2017-12-12
         * @tool   Phpstorm
         */
        //获取商户等级数据
        $datas = Sclass::all();
        return view('admin.shop.add',compact('datas'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //进行验证
       $this -> validate($request,[
           'shopname'    => 'required|max:32',
           'contactman'  => 'required|max:32',
           'contacttel'  => 'required',
           'referral'    => 'required|max:255',
           'mobile'      => 'required|numeric',
           'entertime'   => 'required',
           'remark'      => 'max:255',
           'address'     => 'required|max:255',
           'addressmore' => 'required|max:255',
       ],[
           'shopname.required'    => '缺少店铺名称',
           'shopname.max'         => '店铺名称过长',
           'contactman.required'  => '缺少联系人姓名',
           'contactman.max'       => '联系人姓名过长',
           'contacttel.required'  => '不能为空',
           'referral.required'    => '简介需要填写',
           'referral.max'         => '简介过长',
           'mobile.required'      => '缺少手机号',
           'mobile.numeric'       => '必须是手机号',
           'entertime.required'   => '必须选择添加时间',
           'address.required'     => '地址需要填写',
           'address.max'          => '地址长度过长',
           'addressmore.required' => '详细地址需要填写',
           'addressmore.max'      => '详细地址太长',
       ]);
       //自定义手机号正则验证
       
       //获取各个数据
        $mobile = Input::get('mobile');
        if(!(preg_match("/^1[34578]{1}\d{9}$/", $mobile)))
        return back() -> with(['info'=>'手机号码不正确']);
        $shopname = trim(Input::get('shopname'));
        $contactman = trim(Input::get('contactman'));
        $contacttel = Input::get('contacttel');
        $address = trim(Input::get('address'));
        $referral = trim(Input::get('referral'));
        $addressmore = trim(Input::get('addressmore'));
        $sclass_id = Input::get('sclass_id');
        $remark = Input::get('remark');
        $closeshop = Input::get('closeshop');
        $status = Input::get('status');
        //将传递过来的时间转变为时间戳
        $entertime =  strtotime(Input::get('entertime'));
        //根据slcassid获取有效期
        $effecttime = Sclass::where('id',$sclass_id)->value('effecttime');
        //获取有效期到期时间
        $expiretime = strtotime("+".$effecttime ."year",strtotime(Input::get('entertime')));
        //将头像存入七牛
        if(!($request -> hasFile('file'))){
            return back() -> with(['info'=>'没有添加图片,请添加图片']);
        }else{
            $file = Input::file('file');
            $extension = strtolower($file -> getClientOriginalExtension());
            $clientName = $file -> getClientOriginalName();
            if(!in_array($extension,['png','jpg']))
            return back() -> with(['info'=>'需要png类型或者jpg类型']);
            //首先获取它的扩展名
            //上传到七牛
            $disk = QiniuStorage::disk('qiniu');
            $newName = 'store/'.md5(date('Y-m-d H:i:s').$clientName).".".$extension;
            $bool = $disk -> put($newName,file_get_contents($file->getRealPath()));
            if($bool){
                //将数据插入数据库
                $res = Shop::insert(['shopname'=>$shopname,'contactman'=>$contactman,'shoppic'=>$newName,'closeshop'=>$closeshop,'mobile'=>$mobile,'referral'=>$referral,'address'=>$address,'addressmore'=>$addressmore,'remark'=>$remark,'contacttel'=>$contacttel,'sclass_id'=>$sclass_id,'entertime' => $entertime,'status'=>$status,'changetime' =>$entertime,'expiretime'=>$expiretime]);
                if($res)
                return back() -> with(['info' => '信息添加成功']);
                return back() -> with(['info' => '信息添加失败']);
            }else{
                return back()->with(['info'=>'头像存入七牛失败']);
            }
        }
        //默认的改变时间是和添加的时间是一样的
        //将数据插入数据库
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $datas  = Shop::where('shopid',$id)->first();
        $sdatas = Sclass::where('id',$datas['sclass_id'])->select('rank')->first();
        $now_time = time();
        return view('admin.shop.show',compact('datas','sdatas','now_time'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {

        //根据id获取sclassid
        $sdatas   = Shop::where('shopid',$id)->first();
        $datas    = Sclass::all();
        $now_time = time();
        return view('admin.shop.edit',compact('sdatas','datas','now_time'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //数据验证
       $this -> validate($request,[
           'shopname'    => 'required|max:32',
           'contactman'  => 'required|max:32',
           'contacttel'  => 'required',
           'referral'    => 'required|max:255',
           'mobile'      => 'required|numeric|unique:shops,mobile,'.$id.',shopid',
           'remark'      => 'max:255',
           'address'     => 'required|max:255',
           'addressmore' => 'required|max:255',
       ],[
           'shopname.required'    => '缺少店铺名称',
           'shopname.max'         => '店铺名称过长',
           'contactman.required'  => '缺少联系人姓名',
           'contactman.max'       => '联系人姓名过长',
           'contacttel.required'  => '电话不能为空',
           'referral.required'    => '简介需要填写',
           'referral.max'         => '简介过长',
           'mobile.required'      => '缺少手机号',
           'mobile.numeric'       => '必须是手机号',
           'mobile.unique'        => '手机号已经使用',
           'address.required'     => '地址需要填写',
           'address.max'          => '地址长度过长',
           'addressmore.required' => '详细地址需要填写',
           'addressmore.max'      => '详细地址太长',
       ]);
       //自定义手机号正则验证
       //获取各个数据
        $mobile = Input::get('mobile');
        if(!(preg_match("/^1[34578]{1}\d{9}$/", $mobile)))
        return back() -> with(['info'=>'手机号码不正确']);
        //获取数据
        $shopname = trim(Input::get('shopname'));
        $shoppic = Input::get('shoppic');
        $contactman = trim(Input::get('contactman'));
        $contacttel = Input::get('contacttel');
        $address = trim(Input::get('address'));
        $referral = trim(Input::get('referral'));
        $addressmore = trim(Input::get('addressmore'));
        $sclass_id = Input::get('sclass_id');
        $remark = Input::get('remark');
        $closeshop = Input::get('closeshop');
        $status = Input::get('status');
        $changetime = strtotime(Input::get('changetime'));
        $now_sclassid =  Input::get('now_sclassid');
        $expiretime = Input::get('expiretime');
        if($sclass_id != $now_sclassid){
            //说明用户套餐变更,则有一个套餐变更数据
            $changetime = time();
            //根据slcassid获取有效期
            $effecttime = Sclass::where('id',$now_sclassid)->value('effecttime');
            //获取有效期到期时间
            $expiretime = strtotime("+".$effecttime ."year",$changetime);
        }
        //判断是否有图片传来//如果没有，则不上传图片
        if(!($request -> hasFile('file'))){
            //则直接进行数据更新
            $res = Shop::where('shopid',$id)->update(['shopname'=>$shopname,'contactman'=>$contactman,'closeshop'=>$closeshop,'mobile'=>$mobile,'referral'=>$referral,'address'=>$address,'addressmore'=>$addressmore,'remark'=>$remark,'contacttel'=>$contacttel,'sclass_id'=>$sclass_id,'status'=>$status,'changetime' =>$changetime,'expiretime'=>$expiretime]);
            if($res)
            return back() -> with(['info'=>'更新成功']);
            return back() -> with(['info'=>'更新失败']);
        }
        if($request -> hasFile('file')){
            //说明有头像信息传来
            $file = Input::file('file');
            $extension = strtolower($file -> getClientOriginalExtension());
            if(!in_array($extension,['png','jpg']))
            return back() -> with(['info'=>'需要ping类型或者jpg类型']);
            //首先获取扩展名
            $clientName = $file -> getClientOriginalName();
            $disk = QiniuStorage::disk('qiniu');
            $NewShoppic = 'store/'.md5(date('Y-m-d H:i:s').$clientName).".".$extension;
            $bool = $disk -> put($NewShoppic,file_get_contents($file->getRealPath()));
            if($bool){
                //将数据插入数据库
                $res = Shop::where('shopid',$id)->update(['shopname'=>$shopname,'shoppic'=>$NewShoppic,'contactman'=>$contactman,'closeshop'=>$closeshop,'mobile'=>$mobile,'referral'=>$referral,'address'=>$address,'addressmore'=>$addressmore,'remark'=>$remark,'contacttel'=>$contacttel,'sclass_id'=>$sclass_id,'status'=>$status,'changetime' =>$changetime,'expiretime'=>$expiretime]);
                if($res){
                    $delete = $disk -> delete($shoppic);
                    if($delete)
                    return back()->with(['info'=>'更新成功']);
                    return back()->with(['info'=>'更新成功,删除七牛图片失败地址:'.$shoppic]);
                }else{
                    return back() -> with(['info'=>'更新失败,图片已经传到七牛云,地址是:'.$NewShoppic]);
                }
            }else{
                return back() -> with(['info'=>'图片没有传入七牛，请重新上传']);
            }

        }

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $shoppic = Shop::where('shopid',$id)->value('shoppic');
        $res = Shop::where('shopid',$id)->delete();
        if($res){
            $disk = QiniuStorage::disk('qiniu');
            $bool = $disk -> delete($shoppic);
            if($bool){
                return Response() -> json(['status'=>'success','msg'=>'删除成功']);
            }else{
                return Response() -> json(['status'=>'error','msg'=>'删除七牛图片失败地址:'.$shoppic]);
            }
          
        }
        
        return Response() -> json(['status'=>'error','msg'=>'删除失败']);
    }
    //查看文章
    public function article_show($id){
       //这是店铺id。通过店铺id获取内容
        $datas = ShopArticle::where('shopid',$id)->select('aid','title','senddate','pageview')->paginate('3');
        return view('admin.shoparticle.index',compact('datas'));
    }
}
